import {Component, OnInit} from '@angular/core';
import {Command} from '../../../../shared/toolbar.service';
import {BladeData} from '../../../../shared/blade/blade-data';
import {Blade} from '../../../../shared/blade/blade.model';
import {FormGroup, FormControl, FormBuilder, Validators} from '@angular/forms';
import {BladeContainerBase} from '../../../../shared/blade/blade-container-base';
import {MenuParam} from '../../../../entity/menu-param.model';
import {MenuParamService} from '../../../../service/menu_param.service';
import {Observable} from 'rxjs/Rx';

@Component({
  selector: 'app-menu-param-edit',
  templateUrl: './menu-param-edit.component.html',
  styleUrls: ['./menu-param-edit.component.css']
})
export class MenuParamEditComponent extends BladeContainerBase<MenuParam> {

  constructor(
    private fb: FormBuilder,
    private menuParamService: MenuParamService) {
    super(fb);
  }

  ngOnInit(): void {
    //编辑时注册按钮和按钮命令
    if (!this.isNew) {
      this.commands = [
        new Command('save', '保存', 'fa fa-save', 'setofkey:update', (blade) => this.exeSaveChange(blade), (blade) => this.canSaveChange(blade)),
        new Command('reset', '重置', 'fa fa-save', 'setofkey:reset', (blade) => this.exeReset(blade), (blade) => this.canReset(blade)),

      ]
    }
    else {
      this.currentEntity = new MenuParam(0, this.parentEntity.menuId, '', '', '', '', '');
    }
    super.ngOnInit();
  }

  /**
   * 初始化数据
   *
   *
   * @memberof BladeContainerBase
   */
  initData(): any | Observable<any> | Promise<any> {
    this.formPatchValue(this.currentEntity);
  }

  exeSaveChange(blade: any): void {
    this.saveChange();
  }

  canSaveChange(blade: any): boolean {
    return this.hasChange() && !this.hasError();
  }

  exeReset(blade: any): void {
    return this.formGroup.reset(this.currentEntity);
  }

  canReset(blade: any): boolean {
    return this.hasChange();
  }


  /**
   * 创建表单
   *
   *
   * @memberof DicKeyEditComponent
   */
  createForm() {
    this.formGroup = this.fromBuider.group({
      'paramName': [{value: this.currentEntity.paramName, disabled: !this.isNew}, [
        Validators.required,
        Validators.maxLength(50),
      ], (control: FormControl): any => this.menuParamNameAsnyValidator(control)],
      'paramValue': [this.currentEntity.paramValue, [
        Validators.required,
        Validators.maxLength(200)
      ]],
      'paramDesc': [this.currentEntity.paramDesc, [
        Validators.maxLength(200)
      ]],
    });
  }

  /**
   * 设置表单错误对象
   *
   *
   * @memberof BladeContainerBase
   */
  setFormError(): void {
    this.formErrors = {
      'paramName': '',
      'paramValue': '',
      'paramDesc': ''
    };
  }

  /**
   * 设置表单验证信息
   *
   *
   * @memberof BladeContainerBase
   */
  setValidationMessages(): void {
    this.validationMessages = {
      'paramName': {
        'required': '参数名称不能为空。',
        'maxlength': '参数名称不能多于50个字符长度。',
        'exist': '参数名称已存在',
      },
      'paramValue': {
        'required': '参数值不能为空。',
        'maxlength': '参数值不能多于200个字符长度。',
      },
      'paramDesc': {
        'maxlength': '参数描述不能多于200个字符长度。',
      }
    };
  }

  /**
   * 异步校验menuName是否存在
   *
   * @param {FormControl} control
   * @returns {Promise<true>}
   *
   * @memberof DicKeyEditComponent
   */
  menuParamNameAsnyValidator(control: FormControl): any {
    return this.menuParamService.hasMenuParamByParamname(control.value, this.parentEntity.menuId, this.currentEntity.paramId)
      .map(res => res ? {exist: true} : null);
  }

  /**
   * 创建一个数据字典键
   *
   *
   * @memberof DicKeyEditComponent
   */
  onCreate() {
    this.create();
  }

  create(): Promise<boolean> {
    if (!this.hasError()) {
      this.bladeData.isLoading = true;
      let formValue = this.formGroup.value as MenuParam;
      this.currentEntity.paramName = formValue.paramName;
      this.currentEntity.paramValue = formValue.paramValue;
      this.currentEntity.paramDesc = formValue.paramDesc;
      return this.menuParamService.create(this.currentEntity)
        .then(res => {
          if (res) {
            let parentContainerInstance = this.parentBlade.bladeContainerInstance;
            parentContainerInstance.refresh(res);
            this.bladeService.closeBlade(this.currentBlade);
            return true;
          }
        })
        .catch(error => this.bladeData.error = error)
        .then(res => this.bladeData.isLoading = false);
    }
  }

  saveChange(): Promise<boolean> {
    if (this.canSaveChange(this.currentBlade)) {
      this.bladeData.isLoading = true;
      let formValue = this.formGroup.value as MenuParam;
      this.currentEntity.paramName = formValue.paramName;
      this.currentEntity.paramValue = formValue.paramValue;
      this.currentEntity.paramDesc = formValue.paramDesc;
      return this.menuParamService.update(this.currentEntity)
        .then(res => {
          if (res) {
            let parentContainerInstance = this.parentBlade.bladeContainerInstance;
            parentContainerInstance.refresh(res);
            this.bladeService.closeBlade(this.currentBlade);
            return true;
          }
        })
        .catch(error => this.bladeData.error = error)
        .then(res => this.bladeData.isLoading = false);

    }
  }
}


// WEBPACK FOOTER //
// ./src/app/module/admin/menu/menu-param-edit/menu-param-edit.component.ts
